<!--权限管理页-->
<script setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import RoleDialog from './dialog/RoleDialog.vue'; // 假设有一个角色对话框组件

const store = useStore();
const dialogVisible = ref(false);
const currentRole = ref(null);
const roles = ref([]);

const fetchRoles = () => {
  store.dispatch('fetchRoles').then(() => {
    ElMessage.success('角色列表已更新');
  }).catch(() => {
    ElMessage.error('获取角色列表失败');
  });
};

onMounted(() => {
  fetchRoles();
});

const showAddRoleDialog = () => {
  currentRole.value = null; // 清空当前角色
  dialogVisible.value = true; // 显示对话框
};

const handleRoleSubmit = (roleData) => {
  if (roleData.id) {
    store.dispatch('updateRole', roleData).then(() => {
      ElMessage.success('角色更新成功');
      dialogVisible.value = false; // 关闭对话框
      fetchRoles(); // 刷新角色列表
    }).catch(() => {
      ElMessage.error('更新角色失败');
    });
  } else {
    store.dispatch('addRole', roleData).then(() => {
      ElMessage.success('角色添加成功');
      dialogVisible.value = false; // 关闭对话框
      fetchRoles(); // 刷新角色列表
    }).catch(() => {
      ElMessage.error('添加角色失败');
    });
  }
};

const deleteRole = (roleId) => {
  store.dispatch('deleteRole', roleId).then(() => {
    ElMessage.success('角色删除成功');
    fetchRoles(); // 刷新角色列表
  }).catch(() => {
    ElMessage.error('删除角色失败');
  });
};

const editRole = (role) => {
  currentRole.value = role; // 设置当前角色
  dialogVisible.value = true; // 显示对话框
};
</script>

<template>
  <div class="role-management">
    <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
    <el-table :data="roles" style="width: 100%">
      <el-table-column prop="id" label="角色ID" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editRole(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <RoleDialog
      v-model="dialogVisible"
      :currentRole="currentRole"
      @submit="handleRoleSubmit"
    />
  </div>
</template>

<style scoped>
.role-management {
  padding: 20px;
}
</style>